var app = sm("do_App");
var page = sm("do_Page");
var nf = sm("do_Notification");
var hashdata = mm("do_HashData");
var deviceone = require("deviceone");
var http = require("helper/http");
var httpSilence = require("helper/httpSilence");
var imgTool = require("helper/picture");
var helperOpen = require("helper/open");
var mallUrl = require("url/mall");

var updateProductUrl = mallUrl.url.product.doUpdate;//修改商品
var detail4editSpecUrl = mallUrl.url.product.detail4editSpec;//加载商品规格信息

// UI
var headerAout = ui("headerAout");
var aLayoutRoot = ui("aLayoutRoot");
var root = ui("$");
var productId = null;//商品id
var specId = null;
var shopId = null;
var fileDomain = null;//文件服务器地址
var moneyFix =  /^[0-9]*(\.[0-9]{1,2})?$/;

page.on("loaded", function(data) {
	productId = page.getData().productId;
	specId = page.getData().specId;
	initCategory4Product();//初始化商品一级分类
	loadProductData();
});

// 加载头部
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
ui(addheader+".labelTitle").text = "修改商品";
// andriod返回键
page.on("back", function() {
	app.closePage();
});
// 左上角-返回
var headerLeft = ui(addheader + ".headerLeft");
headerLeft.on("touch", function() {
	app.closePage()
});

var layoutMain = ui("do_LinearLayout_main");
/*商品名称*/
var addNameText = layoutMain.add("nameText", "source://view/reuse/form/mutiInput.ui",0,0);
var nameText = ui("nameText");
nameText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "商品名称",
    "hint":"请输入商品名称"
});
nameText.refreshData();
var textName = ui(addNameText+".textInput");

var layoutSection = ui("layoutSection");
/*规格*/
var addSpecText = layoutSection.add("specText", "source://view/reuse/form/mutiInput.ui",0,0);
var specText = ui("specText");
specText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "规格名称",
    "hint":"规格信息",
    "inputType": "ASC"
});
specText.refreshData();
var textSpec = ui(addSpecText+".textInput");
/*价格*/
var addPriceText = layoutSection.add("priceText", "source://view/reuse/form/mutiInput.ui","specText");
var priceText = ui("priceText");
priceText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "价格",
    "hint":"请输入商品实际销售价格",
    "inputType": "DECIMAL"
});
priceText.refreshData();
var textPrice = ui(addPriceText+".textInput");
textPrice.on("focusOut", function(data, e) {
	if(!moneyFix.test(textPrice.text)){
		nf.toast("请输入正确的价格（保留两位小数）");
	}
})
/*原价*/
var addMarketPriceText = layoutSection.add("marketPriceText", "source://view/reuse/form/mutiInput.ui","priceText");
var marketPriceText = ui("marketPriceText");
marketPriceText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "原价",
    "hint":"请输入商品原价",
    "inputType": "DECIMAL"
});
marketPriceText.refreshData();
var textMarketPrice = ui(addMarketPriceText+".textInput");
textMarketPrice.on("focusOut", function(data, e) {
	if(!moneyFix.test(textMarketPrice.text)){
		nf.toast("请输入正确的原价（保留两位小数）");
	}
})
/*计量单位*/
var addUnitText = layoutSection.add("unitText", "source://view/reuse/form/mutiInput.ui","marketPriceText");
var unitText = ui("unitText");
unitText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "计量单位",
    "hint":"如：个、打",
    "inputType": "ASC"
});
unitText.refreshData();
var textUnit = ui(addUnitText+".textInput");
/*库存*/
var addStockText = layoutSection.add("stockText", "source://view/reuse/form/mutiInput.ui","unitText");
var stockText = ui("stockText");
stockText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "库存",
    "hint":"请输入商品库存",
    "inputType": "PHONENUMBER"
});
stockText.refreshData();
var textStock = ui(addStockText+".textInput");
/*品牌*/
var addBrandNameText = layoutSection.add("brandNameText", "source://view/reuse/form/mutiInput.ui","stockText");
var brandNameText = ui("brandNameText");
brandNameText.bindData(hashdata);
hashdata.addData({
    "textTitle" : "品牌",
    "hint":"请输入商品品牌",
    "inputType": "ASC"
});
brandNameText.refreshData();
var textBrandName = ui(addBrandNameText+".textInput");

var textResume = ui("textResume");
//加载商品信息
function loadProductData(){
	if(productId == null){
		return;
	}
	http.post(detail4editSpecUrl, {productId: productId,id:specId}, function(data) {
		var mallProduct = data.mallProduct;
		var productSpec =  data.mallProductSpec;
		if(mallProduct == null){
		 	nf.toast("该商品不存在！");
		 	app.closePage();
		}
		if(productSpec == null){
			nf.toast("商品规格不存在！");
		 	app.closePage();
		}
		textName.text = mallProduct.name;//商品名称
		textResume.text = mallProduct.resume;//描述
		textUnit.text = mallProduct.unit;
		textPrice.text = mallProduct.price+'';//销售价
		textMarketPrice.text = mallProduct.marketPrice+'';//原价【市场价】
		textStock.text = mallProduct.stock;//库存
		textBrandName.text = mallProduct.brandName;//品牌名称
		//规格信息
		textSpec.text = productSpec.specName;
		textPrice.text = productSpec.price+'';//销售价
		textMarketPrice.text = productSpec.marketPrice+'';//原价【市场价】
		textStock.text = productSpec.stock;//库存
		
		fileDomain = mallProduct.fileDomain;//文件服务器地址
		shopId = mallProduct.shopId;
		categoryId = mallProduct.categoryId;
		categoryName = mallProduct.categoryName;
		isAllNew = mallProduct.isAllNew;
		var imgLst = mallProduct.imgLst;//图片短url列表
		for(var i in imgLst){
			listdataImg1.addOne({"imgPath" : fileDomain+""+imgLst[i]});
		}
		imgGrid1.refreshItems();
		
		var resumeImgLst = mallProduct.resumeImgLst//图片短url列表
		for(var i in resumeImgLst){
			listdataImg2.addOne({"imgPath" : fileDomain+""+resumeImgLst[i]});
		}
		imgGrid2.refreshItems();		
		
		if(isAllNew == "1"){
			checkRadio(0);//全新
		}else{
			checkRadio(1);//二手
		}
	})
}
/** **************点击-添加商品封面图片-begin***************/
var imgCoverMaxCount = 5;//最多上传5张封面
var imgGrid1 = ui("imgGridCover");
var listdataImg1 = mm("do_ListData");
imgGrid1.bindItems(listdataImg1);

ui("aLayoutImgCover").on("touch", function(data, e) {
	var lessImgCount = imgCoverMaxCount-listdataImg1.getCount();
	if(lessImgCount<=0){
		nf.toast("最多只能上传"+imgCoverMaxCount+"张图片.");
		return;
	}
	imgTool.imgMulti(lessImgCount, selectImgBack1);
});
function selectImgBack1(imgList) {
	listdataImg1.addData(imgList.map(function(path) {
		return {
			"imgPath" : path
		}
	}));
	imgGrid1.refreshItems();
}
imgGrid1.on("touch", function(data, e) {
	listdataImg1.removeData([ data ]);
	imgGrid1.refreshItems();
});
/** **************点击-添加商品封面图片-end*****************/

/** **************点击-添加商品详情图片-begin***************/
var imgResumeMaxCount = 5;//最多上传5张详情图片
var imgGrid2 = ui("imgGridResume");
var listdataImg2 = mm("do_ListData");
imgGrid2.bindItems(listdataImg2);

ui("aLayoutImgResume").on("touch", function(data, e) {
	var lessImgCount = imgResumeMaxCount-listdataImg2.getCount();
	if(lessImgCount<=0){
		nf.toast("最多只能上传"+imgResumeMaxCount+"张图片.");
		return;
	}
	imgTool.imgMulti(lessImgCount, selectImgBack2);
});
function selectImgBack2(imgList) {
	listdataImg2.addData(imgList.map(function(path) {
		return {
			"imgPath" : path
		}
	}));
	imgGrid2.refreshItems();
}
imgGrid2.on("touch", function(data, e) {
	listdataImg2.removeData([ data ]);
	imgGrid2.refreshItems();
});
/** **************点击-添加商品详情图片-end*****************/
/***********选择分类begin**************/
var categoryId = null;
var categoryName = null;
//初始化商品一级分类
var levle1List4Product = null;
function initCategory4Product(){
	httpSilence.post(mallUrl.url.category.firstLevel, {}, function(data) {
		levle1List4Product = data.categoryList;
	})
}

var addCategoryPicker = root.add("typeList","source://view/qshop/manage/product/category.ui",0,0);
ui("aLayoutCategory").on("touch","",300,function(){
	page.hideKeyboard();
	if(levle1List4Product!=null && levle1List4Product.length>0){
		page.fire("categoryList",levle1List4Product);
		page.fire("categorys","true");
	}
});


page.on("refreshCategory4Product",function(data){
	var typeCategoryStr = ui("labelCategory");
	if(data){
		if(data.sid != null){//如果有二级分类
			categoryId = data.sid;
			categoryName = data.sname;
			ui("labelCategory").text = data.bname + " / " + data.sname;
		}else if(data.bid != null){//如果只有一级分类
			categoryId = data.bid;
			categoryName = data.bname;
			ui("labelCategory").text = data.bname;
		}else{
			categoryId = null;
			categoryName = '';
			ui("labelCategory").text = '';
		}
	}else{
		categoryId = null;
		categoryName = '';
		ui("labelCategory").text = '';
	}
});
/***********选择分类end**************/

/*************选择成色begin**************/
var isAllNew = 1;//是否全新的:1-是;2-否
var radioItem=[ui("imgAllNew"),ui("imgSecondHand")]
ui("layOutAllNew").on("touch",function(data,e){//点击【全新】
	checkRadio(0);
	isAllNew = 1;
})
ui("layOutSecondHand").on("touch",function(data,e){//点击【二手】
	checkRadio(1);
	isAllNew = 2;
})

function checkRadio(index){
	for (var i = 0; i < radioItem.length; i++) {
		if(i==index){
			radioItem[i].source="source://image/common/radiocheck.png";
		}else{
			radioItem[i].source="source://image/common/radio.png";
		}
	}
}
/************选择成色end***************/

ui("btnEdit").on("touch", "", 5000, function() {
	doUpdateProduct();
})

//提交修改
function doUpdateProduct() {
	page.hideKeyboard();
	var productName = textName.text;//商品名称
	var resume = textResume.text;//描述
	var unit = textUnit.text;
	var specName = textSpec.text;
	var price = textPrice.text;//销售价
	var marketPrice = textMarketPrice.text;//原价【市场价】
	var stock = textStock.text;//库存
	var brandName = textBrandName.text;//品牌名称
	
	if (productName == '' || productName == null) {
		nf.toast("亲，请输入商品名称。");
		return;
	}
	if (resume == '' || resume == null) {
		nf.toast("亲，请填写商品描述。");
		return;
	}
	if (categoryId == '' || categoryId == null) {
		nf.toast("亲，请选择商品分类。");
		return;
	}
	if (specName == '' || specName == null) {
		nf.toast("亲，请输入商品规格名称。");
		return;
	}
	if (price == '' || price == null) {
		nf.toast("亲，请填写商品价格。");
		return;
	}
	if(!moneyFix.test(price)){
		nf.toast("请输入正确的商品价格（保留两位小数）");
		return;
	}
	if (unit == '' || unit == null) {
		nf.toast("亲，请填写计量单位。");
		return;
	}
	if (marketPrice == '' || marketPrice == null) {
		nf.toast("亲，请填写商品原价。");
		return;
	}
	if(!moneyFix.test(marketPrice)){
		nf.toast("请输入正确的原价（保留两位小数）");
		return;
	}
	if (stock == '' || stock == null) {
		nf.toast("亲，请填写商品库存。");
		return;
	}
	if(isNaN(stock)){
		textStock.text = "";
		nf.toast("库存必须是数字");
		return;
	}
	if (listdataImg1.getCount() == 0) {
		nf.toast("亲，请添加商品封面图片。");
		return;
	}
	if (listdataImg2.getCount() == 0) {
		nf.toast("亲，请添加商品详情图片。");
		return;
	}
	if(shopId == '' || stock == shopId){
		nf.toast("店铺id为空。");
		return;
	}
	
	var imgFiles = [];
	
	var fullImgLst4keepOld = [];//保留下来的旧的--商品图片
	var fullResumeImgLst4keepOld = [];//保留下来的旧的--详情图片
	
	var imgCount4New = 0;//新增的商品图片
	var impPath4temp = null;
	for (var i = 0; i < listdataImg1.getCount(); i++) {
		impPath4temp = listdataImg1.getOne(i).imgPath;
		if(impPath4temp.indexOf(fileDomain) > -1){//如果包括文件服务器路径，说明是旧的
			fullImgLst4keepOld.push(impPath4temp);//旧的
		}else{
			imgFiles.push(impPath4temp);//新添加的图片
			imgCount4New ++;
		}
	}
	for (var i = 0; i < listdataImg2.getCount(); i++) {
		impPath4temp = listdataImg2.getOne(i).imgPath;
		if(impPath4temp.indexOf(fileDomain) > -1){//如果包括文件服务器路径，说明是旧的
			fullResumeImgLst4keepOld.push(impPath4temp);//旧的
		}else{
			imgFiles.push(impPath4temp);//新添加的图片
		}
	}
	var imgLst4keepOld = removeFileDomainUrl(fullImgLst4keepOld);
	var resumeImgLst4keepOld = removeFileDomainUrl(fullResumeImgLst4keepOld);
	
	if (imgFiles.length > 0) {
		http.form(imgFiles, "mall", function(imgDatas) {
			var string4imgs = imgDatas.path;// 返回图片云端路径（后部份）用分号隔开
			var imgs=string4imgs.split(";");
			var imgFiles4Cover = [];//封面-图片列表
			var imgFiles4Resume = [];//详情-图片列表
			for (var i = 0; i < imgs.length; i++) {
				if(i < imgCount4New){
					imgFiles4Cover.push(imgs[i]);
				}else{
					imgFiles4Resume.push(imgs[i]);
				}
			}
			var newImg = imgLst4keepOld.concat(imgFiles4Cover).join(";"); //合并两数组
			var newResumeImg = resumeImgLst4keepOld.concat(imgFiles4Resume).join(";");
			var params = {
				"id": productId,
				"shopId" : shopId,
				"name" : productName,
				"resume" : resume,
				"categoryId" : categoryId,
				"price" : price,
				"marketPrice" : marketPrice,
				"stock" : stock,
				"brandName" : brandName,
				"img" : newImg,
				"resumeImg" : newResumeImg,
				"unit" : unit,
				"isAllNew" : isAllNew,
				"feature" : "" //商品特色描述
			};

			var specs = [];
			var spec = {"id":"","productId":"","price":"","marketPrice":"","stock" : ""};
			spec.id = specId;
			spec.productId = productId;
			spec.price = price;
			spec.marketPrice = marketPrice;
			spec.stock = stock;
			spec.specName = specName;
			specs.push(spec);
			params.productSpecLst = specs;
			
			http.post(updateProductUrl, params, function(data) {
				nf.toast("修改成功");
				app.closePage({mall_edit_productSpec:true});
			})
		});
	}else{
		var newImg = imgLst4keepOld.join(";"); //合并两数组
		var newResumeImg = resumeImgLst4keepOld.join(";");
		var params = {
			"id": productId,
			"shopId" : shopId,
			"name" : productName,
			"resume" : resume,
			"categoryId" : categoryId,
			"price" : price,
			"marketPrice" : marketPrice,
			"stock" : stock,
			"brandName" : brandName,
			"img" : newImg,
			"resumeImg" : newResumeImg,
			"unit" : unit,
			"isAllNew" : isAllNew,
			"feature" : "" //商品特色描述
		};
		
		var specs = [];
		var spec = {"id":"","productId":"","price":"","marketPrice":"","stock" : "","specName":""};
		spec.id = specId;
		spec.productId = productId;
		spec.price = price;
		spec.marketPrice = marketPrice;
		spec.stock = stock;
		spec.specName = specName;
		specs.push(spec);
		params.productSpecLst = specs;
		
		http.post(updateProductUrl, params, function(data) {
			nf.toast("修改成功");
			app.closePage({mall_edit_productSpec:true});
		})
	}
}

//点击背景隐藏输入键盘
root.on("touch",function(){
	page.hideKeyboard();
})

function removeFileDomainUrl(urlList){
	var newUrlList  = [];
	if(urlList == null || urlList.length==0){
		return newUrlList;
	}
	var newUrl = "";
	for(var i in urlList){
		newUrl = urlList[i].replace(fileDomain,"");
		newUrlList.push(newUrl);
	}
	return newUrlList;
}